import Alertift
import Kingfisher
import ProgressHUD
import UIKit

class ProfileViewController: UIViewController {

  private let taskId: Int

  init(taskId: Int) {
    self.taskId = taskId
    super.init(nibName: nil, bundle: nil)
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  var userData: UserData = UserDefaults.baoDan.loadUserDataFromUserDefaults()!

  // MARK: - UI Components
  let viewBackgroundColor = UIColor(red: 0.96, green: 0.96, blue: 0.97, alpha: 1)
  private let gradientLayer: CAGradientLayer = {
    let layer = CAGradientLayer()
    layer.locations = [0, 1]
    layer.startPoint = CGPoint(x: 0.5, y: 0)
    layer.endPoint = CGPoint(x: 0.5, y: 1)
    return layer
  }()

  private let avatarImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.layer.cornerRadius = 30  // 增大头像尺寸
    imageView.clipsToBounds = true
    imageView.contentMode = .scaleAspectFill
    imageView.translatesAutoresizingMaskIntoConstraints = false
    return imageView
  }()

  private let nameLabel: UILabel = {
    let label = UILabel()
    label.font = .systemFont(ofSize: 20, weight: .bold)
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
  }()

  private let phoneLabel: UILabel = {
    let label = UILabel()
    label.font = .systemFont(ofSize: 16)
    label.textColor = .gray
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
  }()

  private let logoutButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("退出登录", for: .normal)
    button.backgroundColor = .white
    button.setTitleColor(.gray, for: .normal)
    button.layer.cornerRadius = 4  // 圆角按钮
    button.translatesAutoresizingMaskIntoConstraints = false
    return button
  }()

  // MARK: - Lifecycle
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = viewBackgroundColor
    setupUI()
    configureUI()
    gradientLayer.colors = [
      UIColor(red: 1, green: 0.97, blue: 0.9, alpha: 1).cgColor,
      viewBackgroundColor.cgColor,
    ]
    // 添加渐变色图层到视图的layer中
    view.layer.insertSublayer(gradientLayer, at: 0)
  }

  let mobPageName = "app-我的"
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    MobClick.beginLogPageView(mobPageName)
  }

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    MobClick.endLogPageView(mobPageName)
  }

  override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    gradientLayer.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 240)
  }

  // MARK: - UI Setup
  private func setupUI() {
    view.layer.insertSublayer(gradientLayer, at: 0)
    title = "我的"

    let gearImage = UIImage(systemName: "gear")?.withConfiguration(
      UIImage.SymbolConfiguration(pointSize: 18, weight: .medium))
    navigationItem.rightBarButtonItem = UIBarButtonItem(
      image: gearImage, style: .plain, target: self, action: #selector(settingsButtonTapped))
    navigationItem.rightBarButtonItem?.tintColor = .orange

    view.addSubview(avatarImageView)
    view.addSubview(nameLabel)
    view.addSubview(phoneLabel)
    view.addSubview(logoutButton)

    NSLayoutConstraint.activate([
      avatarImageView.topAnchor.constraint(
        equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40),
      avatarImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
      avatarImageView.widthAnchor.constraint(equalToConstant: 60),  // 增大头像尺寸
      avatarImageView.heightAnchor.constraint(equalToConstant: 60),

      nameLabel.topAnchor.constraint(equalTo: avatarImageView.topAnchor, constant: 4),
      nameLabel.leadingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: 12),

      phoneLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 8),
      phoneLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor),

      logoutButton.bottomAnchor.constraint(
        equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
      logoutButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      logoutButton.widthAnchor.constraint(equalToConstant: 335),  // 设置按钮宽度
      logoutButton.heightAnchor.constraint(equalToConstant: 44),
    ])
  }

  private func configureUI() {
    nameLabel.text = userData.userName
    if let imageUrl = URL(string: userData.headImgUrl) {
      avatarImageView.kf.setImage(with: imageUrl, placeholder: UIImage(named: "default_avatar"))
    }
    phoneLabel.text = userData.phone
    logoutButton.addTarget(self, action: #selector(logoutButtonTapped), for: .touchUpInside)
  }

  // MARK: - Actions
  @objc private func logoutButtonTapped() {
    Alertift.alert(title: "提醒", message: "确定要退出登录吗?")
      .action(.cancel("取消"))
      .action(.destructive("确定")) { [weak self] in
        self?.logoutNetWork()
      }
      .show()
  }

  @objc private func settingsButtonTapped() {
    let vc = SettingViewController()
    vc.hidesBottomBarWhenPushed = true
    navigationController?.pushViewController(vc, animated: true)
  }

  private func logoutNetWork() {
    MobClick.event("logout", label: "iOS")

    // TODO: 实现退出登录逻辑
    HttpClient.shared.post(endpoint: "/logout", body: [:]) {
      (result: Result<String, NetworkError>) in
      DispatchQueue.main.async {

        switch result {
        case .success(_):
          if let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate
            as? SceneDelegate
          {
            let window = sceneDelegate.window
            UserDefaults.baodan.removeUserDataFromUserdefaults()

            // 切换根视图控制器
            UIView.transition(
              with: window!, duration: 0.5, options: .transitionCrossDissolve,
              animations: {
                window?.rootViewController = WelcomeViewController()  // 登录成功后，切换到主页面
              })
          }
        case .failure(let error):

          // ❌ 处理错误
          switch error {
          case .serverError(let code):
            ProgressHUD.failed("服务器错误: \(code)")
          case .noData:
            ProgressHUD.failed("未收到服务器响应")
          case .decodingError:
            ProgressHUD.failed("数据解析错误")
          case .invalidURL:
            ProgressHUD.failed("无效的URL")
          case .customError(let message):
            ProgressHUD.failed(message)
          }
        }
      }
    }
  }
}
